package com.study.dao.impl;

import com.alibaba.druid.pool.DruidPooledConnection;
import com.study.dao.AccountDao;
import com.study.pojo.Account;
import com.study.utils.CollectionUtils;
import com.study.utils.DruidUtils;

import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @author Qi XueSong
 */
public class AccountDaoImpl implements AccountDao {

    private CollectionUtils collectionUtils;

    public void setCollectionUtils(CollectionUtils collectionUtils) {
        this.collectionUtils = collectionUtils;
    }

    public Account queryAccountByCardNo(String cardNo) throws Exception {
        //从连接池中获取连接
        DruidPooledConnection conn = collectionUtils.getConnection();
        String sql = "select * from account where cardNo=?";
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        preparedStatement.setObject(1,cardNo);
        ResultSet resultSet = preparedStatement.executeQuery();

        //解析查询结果
        Account account = new Account();
        while (resultSet.next()){
            account.setCardNo(resultSet.getString("cardNo"));
            account.setName(resultSet.getString("name"));
            account.setMoney(resultSet.getInt("money"));
        }
        //关闭资源
        resultSet.close();
        preparedStatement.close();
        //由于要保持当前线程中的操作在一个连接中，所以不能关闭连接
        //conn.close();

        return account;
    }

    public int updateAccountByCardNo(Account account) throws Exception {
        //从连接池中获取连接
        DruidPooledConnection conn = DruidUtils.getInstance().getConnection();

        String sql = "update account set money=? where cardNo=?";
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        preparedStatement.setInt(1,account.getMoney());
        preparedStatement.setString(2,account.getCardNo());
        int count = preparedStatement.executeUpdate();

        //关闭资源
        preparedStatement.close();
        //由于要保持当前线程中的操作在一个连接中，所以不能关闭连接
        //conn.close();
        return count;
    }
}
